package com.ctl.shardingsphere.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctl.shardingsphere.mapper.DeviceMapper;
import com.ctl.shardingsphere.model.Device;
import com.ctl.shardingsphere.model.query.DeviceQuery;
import com.ctl.shardingsphere.service.DeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Optional;

/**
 * @Classname UserServiceImpl
 * @Description 用户服务实现类
 * @Author ctl
 * @Date 2019-06-28 17:32
 * @Version 1.0
 */
@Slf4j
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements DeviceService {

    @Override
    public boolean save(Device entity) {
        return super.save(entity);
    }

    @Override
    public List<Device> getDeviceList(DeviceQuery query) {
        Optional.ofNullable(query.getCurrentPage()).orElseGet(() -> {
            query.setCurrentPage(1);
            return query.getCurrentPage();
        });
        Optional.ofNullable(query.getPageSize()).orElseGet(() -> {
            query.setPageSize(10);
            return query.getPageSize();
        });
        LambdaQueryWrapper<Device> objectLambdaQueryWrapper = Wrappers.lambdaQuery();
        objectLambdaQueryWrapper.eq(Device::getCode, query.getCode()); //=
        objectLambdaQueryWrapper.orderByAsc(Device::getId);
        Page<Device> devicePage = new Page<>(query.getCurrentPage(), query.getPageSize());
        devicePage.setSearchCount(true); //是否进行count  是
        devicePage.setOptimizeCountSql(true);
        IPage<Device> deviceIPage = baseMapper.selectPage(devicePage, objectLambdaQueryWrapper);

        if (!CollectionUtils.isEmpty(deviceIPage.getRecords())) {
            deviceIPage.getRecords().stream().forEach(recorc -> System.out.println(JSON.toJSONString(recorc)));
        }
        return baseMapper.selectList(objectLambdaQueryWrapper);
    }


}